package com.gdth.animation;

import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;

public class ExpandCollapseAnimation extends Animation {
	/**
	 * 动画实体
	 */
	private View mAnimatedView;
	
	/**
	 * 实体高度
	 */
	private int mEndHeight;
	
	/**
	 * 用于判断动画类型 collapse (1) and expand (0)
	 */
	private int mType;
	
	/**
	 * 关闭动画
	 */
	public final static int COLLAPSE = 1;
	
	/**
	 * 展开动画
	 */
	public final static int EXPAND = 0;
	
	/**
	 * 用于获取实体属性
	 */
	private LinearLayout.LayoutParams mLayoutParams;

	/**
	 * 构造动画类
	 * @param view 动画实体
	 * @param type 动画类型
	 */
	public ExpandCollapseAnimation(View view, int type) {
		mAnimatedView = view;
		mEndHeight = mAnimatedView.getMeasuredHeight();
		
		int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        mEndHeight = view.getMeasuredHeight();
        
        mLayoutParams = ((LinearLayout.LayoutParams) view.getLayoutParams());
		mType = type;
		
		if(mType == EXPAND) {
			mLayoutParams.bottomMargin = -mEndHeight;
		} else {

			mLayoutParams.bottomMargin = 0;
		}
		
		view.setVisibility(View.VISIBLE);

		final ViewTreeObserver vto = view.getViewTreeObserver(); 
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { 
            public boolean onPreDraw() { 
//                vto.removeOnPreDrawListener(this);
//                mEndHeight = view.getMeasuredHeight(); 
//                mLayoutParams = ((LinearLayout.LayoutParams) view.getLayoutParams());
//        		mType = type;
//        		
//        		if(mType == EXPAND) {
//        			mLayoutParams.bottomMargin = -mEndHeight;
//        		} else {
//        			mLayoutParams.bottomMargin = 0;
//        		}
//        		
//        		view.setVisibility(View.VISIBLE);
//                return true; 
            	
            	return false;
            } 
        });

		
	}

	@Override
	protected void applyTransformation(float interpolatedTime, Transformation t) {

		super.applyTransformation(interpolatedTime, t);
		if (interpolatedTime < 1.0f) {
			if(mType == EXPAND) {
				mLayoutParams.bottomMargin =  -mEndHeight + (int) (mEndHeight * interpolatedTime);
			} else {
				mLayoutParams.bottomMargin = - (int) (mEndHeight * interpolatedTime);
			}
			//Log.d("ExpandCollapseAnimation", "anim height " + mLayoutParams.bottomMargin);
			mAnimatedView.requestLayout();
		} else {
			if(mType == EXPAND) {
				mLayoutParams.bottomMargin = 0;
				mAnimatedView.requestLayout();
			} else {
				mLayoutParams.bottomMargin = -mEndHeight;
				mAnimatedView.setVisibility(View.GONE);
				mAnimatedView.requestLayout();
			}
		}
	}

}
